import { defineStore } from 'pinia';
import {MyMenu} from "@/interfaces/interface.ts";
import routes from '@/router/routes.ts'
import {RouteLocationNormalizedLoaded} from "vue-router";
import myLocalStore from "@/composables/myLocalStore.ts";
import MyLocalStore from "@/composables/myLocalStore.ts";
export default defineStore('menu',{
    state:()=>{
        return {
            menus:[] as MyMenu[],
            historyMenu:[] as MyMenu[],
            breadcrumbRoute:null as null | RouteLocationNormalizedLoaded
        }
    },
    getters:{

    },
    actions:{
        init(){
            this.getMenuByRoutes();
            this.historyMenu = myLocalStore().get('history_menu') ?? [];
        },
        setCurrentMenu(route:RouteLocationNormalizedLoaded){
            this.menus?.forEach(pmenu=>{
                pmenu.isChoose = false;
                pmenu.children?.forEach(cmenu=>{
                    cmenu.isChoose = false;
                    if(route.name == cmenu.routeName){
                        pmenu.isChoose = true;
                        cmenu.isChoose = true;
                    }
                })
            })
        },
        getMenuByRoutes(){
            this.menus = routes
                .filter(route=>route.children?.length && route.meta?.menu)
                .map(route=>{
                    let menu = route.meta?.menu as MyMenu;
                    menu.children = route.children?.filter(route=>route.meta?.menu)
                        .map(route=>{
                            return {...route.meta?.menu,routeName:route.name}
                        }) as MyMenu[]
                    return menu;
                })
                .filter(menu=>menu.children?.length)
                .sort((a,b)=>{
                    return (a?.sort ?? 0) - (b?.sort ?? 0)
                }) as MyMenu[]
        },
        addHistoryMenus(route:RouteLocationNormalizedLoaded){
            if (!route.meta?.menu || route?.meta?.notHistory) return;
            //this.breadcrumbRoute = route;
            const hMenu = {...route.meta?.menu,routeName:route.name} as MyMenu;
            const isHas = this.historyMenu.some(menu=>menu.routeName == route.name);
            if(!isHas) this.historyMenu.unshift(hMenu);
            if(this.historyMenu.length > 10) this.historyMenu.pop();
            myLocalStore().set('history_menu',this.historyMenu);
        },
        removeHistoryMenu(menu:MyMenu){
            const index = this.historyMenu.indexOf(menu);
            this.historyMenu.splice(index,1);
            MyLocalStore().set('history_menu',this.historyMenu);
        }
    }
});